package org.lzy.shop.viewmodel.repository.lmpl

import org.lzy.shop.Constant
import org.lzy.shop.network.ApiException
import org.lzy.shop.network.KtorApiService
import org.lzy.shop.response.CreateMsgResponse
import org.lzy.shop.response.ItemMsg
import org.lzy.shop.response.MyInfoResponse
import org.lzy.shop.response.UserCountResponse
import org.lzy.shop.util.DataStoreUtils
import org.lzy.shop.viewmodel.repository.BaseRepository
import org.lzy.shop.viewmodel.repository.MineRepository

class MineRepositoryImpl : BaseRepository(),MineRepository {

    // 添加检查token有效性的方法
    private fun checkTokenValid(): Boolean {
        try {
            val token = DataStoreUtils.getToken(Constant.TOKEN)
            return !token.isNullOrEmpty()
        } catch (e: Exception) {
            // 捕获MMKV未初始化等异常
            e.printStackTrace()
            return false
        }
    }


    override suspend fun getMyInfo(): MyInfoResponse? {
        return safeApiCall {
            if (!checkTokenValid()) {
                throw ApiException(-1, "用户未登录")
            }
            val response = KtorApiService.getMyInfo()
            handleResponse(response)
        }
    }

    override suspend fun getUserCount(): UserCountResponse? {
        // 在请求前检查token是否有效
        if (!checkTokenValid()) {
            throw ApiException(-1, "用户未登录")
        }
        return safeApiCall {
            val response = KtorApiService.getUserCount()
            handleResponse(response)
        }
    }

    override suspend fun logout(): Any? {
        // 登出操作不缓存
        return safeApiCall {
            val response = KtorApiService.logoff()
            handleResponse(response)
        }
    }

    override suspend fun createMsg(): CreateMsgResponse? {
        // 创建消息会话不缓存
        return safeApiCall {
            val response = KtorApiService.createMsg()
            handleResponse(response)
        }
    }

    override suspend fun getMsgList(sessionId: Int?, page: String?): MutableList<ItemMsg>? {
        return safeApiCall {
            val response = KtorApiService.getMsgList(sessionId, page)
            handleResponse(response).list
        }
    }

    override suspend fun sendMessage(sessionId: Int?, content: String): Any? {
        // 发送消息不缓存
        return safeApiCall {
            val response = KtorApiService.sendMessage(sessionId, content)
            handleResponse(response)
        }
    }
}